/**
* @Author: zou.yingbin
* @Create  : 2020/10/26 16:14
* @Modify  : 2020/10/26 16:14
 */

package main

import (
	"sync"
	"time"
)

// 委托单信息.
type orderReqInfo struct {
	strAcc     string
	serialNum  uint32
	orderId    uint64
	orderQty   uint64
	tradeQty   uint64
	tReq       time.Time
	tRsp       time.Time
	tTrade     time.Time
	tReqSpan   int64
	tTradeSpan int64
}

type stOrderLog struct {
	mOrderReq map[uint32]orderReqInfo
	mTradeNtf map[uint64]orderReqInfo
	mLock     sync.RWMutex
}

// 初始化
func (r *stOrderLog) Init() {
	r.mOrderReq = make(map[uint32]orderReqInfo)
	r.mTradeNtf = make(map[uint64]orderReqInfo)
}

func (r *stOrderLog) addReq(strAcc string, orderQty uint64, serialNum uint32) {
	r.mLock.Lock()
	defer r.mLock.Unlock()
	r.mOrderReq[serialNum] = orderReqInfo{
		strAcc:    strAcc,
		serialNum: serialNum,
		orderId:   0,
		orderQty:  orderQty,
		tradeQty:  0,
		tReq:      time.Now().Local(),
	}
}

func (r *stOrderLog) addRsp(serialNum uint32, orderId uint64, bSuccess bool) {
	r.mLock.Lock()
	defer r.mLock.Unlock()
	if d, ok := r.mOrderReq[serialNum]; ok {
		if bSuccess {
			d.tRsp = time.Now().Local()
			d.tReqSpan = d.tRsp.Sub(d.tReq).Milliseconds()
			d.orderId = orderId
			r.mTradeNtf[d.orderId] = d
		}
		delete(r.mOrderReq, serialNum)
	}
}

func (r *stOrderLog) addTradeNtf(orderId uint64, qty uint64) {
	r.mLock.Lock()
	defer r.mLock.Unlock()
	if d, ok := r.mTradeNtf[orderId]; ok {
		d.tradeQty += qty
		if d.tradeQty >= d.orderQty {
			d.tTrade = time.Now().Local()
			d.tTradeSpan = d.tTrade.Sub(d.tReq).Milliseconds()
			if valLog != nil {
				valLog.Logger().Debugf("%s,%d,%s,%s,%d\n",
					d.strAcc, d.orderId, d.tReq.Format("15:04:05.000"),
					d.tTrade.Format("15:04:05.000"), d.tTradeSpan)
			}
		}
	}
}
